<template>
    <div class="users-container">
      <div class="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!--卡片视图-->
      <el-card class="box-card">
        <el-row :gutter="0">
          <el-col :span="8"><div class="grid-content bg-purple">
            <el-input placeholder="查询用户" v-model="queryInfo.query" clearable @clear="clear">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div></el-col>
          <el-col :span="3"><div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
          </div></el-col>
          <el-col :span="1" style="float: right"><div class="grid-content bg-purple">
            <el-button type="primary" icon="el-icon-refresh" circle @click="getUserList"></el-button>
          </div></el-col>
        </el-row>

        <!--用户列表区-->
        <el-table :data="userInfo.users" style="width: 100%" border stripe>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content=" 编辑 " placement="top" :enterable="false">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content=" 分配角色 " placement="top" :enterable="false">
                <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRolesDialog(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content=" 删除 " placement="top" :enterable="false">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--底部分页-->
        <el-pagination background layout="total,sizes,prev, pager, next" align="left" :page-size="queryInfo.pagesize" :total="userInfo.total"
                       @current-change="pagenumChange" :current-page="queryInfo.pagenum" @size-change="handleSizeChange" :page-sizes="[5,10,15,30,60,120,240,480]">
        </el-pagination>
      </el-card>

      <!--添加用户的对话框-->
      <el-dialog title="添加用户" align="left" :visible.sync="dialogVisible" width="35%" :before-close="handleClose" @close="addformReset">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile "></el-input>
          </el-form-item>
        </el-form>
        <!--底部区-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addformReset">重置</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!--编辑用户对话框-->
      <el-dialog title="修改用户" align="left" :visible.sync="editDialogVisible" width="35%">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px" class="demo-ruleForm">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile "></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!--分配角色的对话框-->
      <el-dialog title="分配角色" align="left" :visible.sync="setRolesDialogVisible" width="35%">
        <div>
          <p>当前用户: {{userRoles.username}}</p>
          <p>当前角色: {{userRoles.role_name}}</p>
          <p>分配新角色:
            <el-select v-model="selectRolesId" placeholder="请选择">
              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoles">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
  import connector from '../../base/interface.js';
    export default {
      name: "Users",
      data(){
        var checkEmail=(rule, value, callback)=>{
          /*自定义校验规则,校验邮箱*/
          var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
          if(reg.test(value)){
            callback();
          }else{
            return callback(new Error('邮箱格式不正确!'));
          }
        }
        var checkMobile=(rule, value, callback)=>{
          /*自定义校验规则校验手机号*/
          var reg= /^[1][3,4,5,6,7,8,9][0-9]{9}$/
          if(reg.test(value)){
            callback();
          }else{
            return callback(new Error('手机号不正确!'));
          }
        }
        /*获取用户列表的参数对象*/
        return{
          queryInfo:{
            'query':'',
            /*当前页*/
            'pagenum':1,
            /*每页显示条数*/
            'pagesize':5
          },
          userInfo:{},
          /*分配角色时展示的用户信息*/
          userRoles:{},
          /*所有角色数据列表*/
          rolesList:[],
          /*选择分配角色的角色id*/
          selectRolesId:null,
          /*添加用户的对话框是否显示*/
          dialogVisible:false,
          /*编辑用户的对话框是否显示*/
          editDialogVisible:false,
          /*分配角色对话框*/
          setRolesDialogVisible:false,
          /*添加用户的表单数据*/
          addForm:{username:'', password:'', email:'', mobile:''},
          /*编辑用户的表单数据*/
          editForm:{username:'', email:'', mobile:''},
          /*添加用户表单验证规则对象*/
          addFormRules:{
            username:[{required:true,message:'请输入用户名', trigger: 'blur'},
              { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
            password:[{required:true,message:'请输入密码', trigger: 'blur'},
              { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }],
            email:[{required:true,message:'请输入邮箱', trigger: 'blur'},{validator:checkEmail,trigger: 'blur'}],
            mobile:[{required:true,message:'请输入手机号', trigger: 'blur'},{validator:checkMobile,trigger: 'blur'}]
          }
        }
      },methods:{
        getUserList(){
          /*获取用户数据列表*/
          connector.getUserList(this.queryInfo).then(res=>{
            this.userInfo=res.data.data;
          })
        },
        handleSizeChange(pagesize){
          /*每页显示多少条,条数改变*/
          this.queryInfo.pagesize=pagesize;
          this.getUserList();
        },
        pagenumChange(page){
          /*table 换页*/
          this.queryInfo.pagenum=page;
          this.getUserList();
        },
        userStateChange(rowObj){
          /*用户状态改变,rowObj: 行对象*/
          connector.updateUsersState(rowObj.id,rowObj.mg_state).then(res=>{
            var {data:data}=res;
            this.$message({message:data.data.username+' 用户 '+data.meta.msg,type:'success'});
          },error => {
            rowObj.mg_state=!rowObj.mg_state;
          });
        },
        clear(){
          /*清空查询用户输入框, 并且查询所有用户*/
          this.getUserList();
        },
        handleClose(){
          /*添加用户的对话框关闭触发*/
          this.dialogVisible=false;
        },
        addformReset(){
          /*添加用户表单重置*/
          this.$refs.addFormRef.resetFields();
        },
        addUser(){
          /*添加用户*/
          this.$refs.addFormRef.validate(vaild=>{
            if(!vaild)return;
            /*发起添加用户请求*/
            connector.addUser(this.addForm).then(res=>{
              var {data:data}=res;
              this.$message({message:data.meta.msg,type:'success'});
              /*重置并关闭*/
              this.$refs.addFormRef.resetFields();
              this.dialogVisible=false;
              this.getUserList();
            })
          })
        },
        editUser(){
          /*编辑用户*/
          this.$refs.editFormRef.validate(vaild=>{
            if(!vaild)return;
            /*发起添加用户请求*/
            connector.editUser(this.editForm).then(res=>{
              var {data:data}=res;
              this.$message({message:data.meta.msg,type:'success'});
              /*重置并关闭*/
              this.$refs.editFormRef.resetFields();
              this.editDialogVisible=false;
              this.getUserList();
            })
          })
        },
        deleteUser(id){
          /*删除用户*/
          this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
          }).then(() => {
            connector.deleteUser(id).then(res=>{
              /*删除成功*/
              var {data:data}=res;
              this.$message({message:data.meta.msg,type:'success'});
              this.getUserList();
            },error => {this.$message.error({message:data.meta.msg});})
          });
        },
        showEditDialog(){
          /*编辑用户操作触发*/
          connector.getUserById(id).then(res=>{
            var {data:data}=res;
            this.editForm=data.data;
          });
          this.editDialogVisible=true;
        },
        showSetRolesDialog(userRoles){
          /*分配角色操作触发*/
          this.userRoles=userRoles;
          /*获取角色列表*/
          connector.getRolesList().then(res=>{
            var {data:data}=res;
            this.rolesList=data.data;
            this.setRolesDialogVisible=true;
          });
        },
        setRoles(){
          /*分配角色*/
          connector.setUserRole(this.userRoles.id,this.selectRolesId).then(res=>{
            /*分配成功*/
            var {data:data}=res;
            this.selectRolesId=null;
            this.setRolesDialogVisible=false;
            this.getUserList();
            this.$message({message:data.meta.msg,type:'success'});
          });
        }
      },
      created() {
        this.getUserList();
      }
    }
</script>

<style lang="scss" scoped>
.users-container{
  .box-card{
    box-shadow:0 2px 2px rgba(0,0,0,0.15);
  }
}
</style>
